# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from wenlincms.utils.models import get_user_model

from wlapps.accounts.models import UCenter

User = get_user_model()


class UCenterInline(admin.StackedInline):
    model = UCenter
    can_delete = False
    readonly_fields = ("wechat", "yue",)


class WLUserAdmin(UserAdmin):
    fieldsets = (
        ('基础信息', {'fields': ('username', 'password', 'last_login', 'date_joined',)}),
        ('admin后台权限', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
    )
    # list_display = ('id', 'username', "get_usertitle", "get_company", "get_ctype", "get_yue", "get_ktdate", "is_active", 'is_staff', 'is_superuser',)
    list_display = ('id', 'username', "get_usertitle", "is_active", 'is_superuser',)

    list_display_links = ('username',)
    ordering = []
    search_fields = ('username',)
    readonly_fields = ['last_login', 'date_joined', ]
    inlines = [UCenterInline, ]

    def get_usertitle(self, obj):
        return obj.u_ucenter.title

    get_usertitle.short_description = "姓名"

    def get_company(self, obj):
        return obj.u_ucenter.company

    get_company.short_description = "公司"

    def get_yue(self, obj):
        return obj.u_ucenter.yue

    get_yue.short_description = "余额"

    def get_ctype(self, obj):
        return obj.u_ucenter.get_ctype_display()

    get_ctype.short_description = "计费类型"

    def get_ktdate(self, obj):
        return obj.u_ucenter.ktdate

    get_ktdate.short_description = "到期日期"

    def save_model(self, request, obj, form, change):
        obj.save()
        # 保存新建的时有对应的ucenter
        if UCenter.objects.filter(userid=obj.id).count() == 0:
            user = User.objects.get(id=obj.id)
            UCenter.objects.create(userid=user)


if User in admin.site._registry:
    admin.site.unregister(User)
admin.site.register(User, WLUserAdmin)
